package com.wei.wiki.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wei.wiki.exception.BusinessException;
import com.wei.wiki.exception.BusinessExceptionCode;
import com.wei.wiki.mapper.ContentMapper;
import com.wei.wiki.mapper.DocInfoMapper;
import com.wei.wiki.mapper.DocMapper;
import com.wei.wiki.pojo.Content;
import com.wei.wiki.pojo.Doc;
import com.wei.wiki.pojo.DocExample;
import com.wei.wiki.req.DocQueryReq;
import com.wei.wiki.req.DocSaveReq;
import com.wei.wiki.resp.DocQueryResp;
import com.wei.wiki.resp.PageResp;
import com.wei.wiki.service.DocService;
import com.wei.wiki.service.WebSocketService;
import com.wei.wiki.util.CopyUtil;
import com.wei.wiki.util.RedisUtil;
import com.wei.wiki.util.RequestContext;
import com.wei.wiki.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/*
 * @author : ShunWei
 * @date : 2022/1/27 20:54
 * @Description:
 */
@Service
public class DocServiceImpl implements DocService {
    private DocMapper docMapper;

    private ContentMapper contentMapper;

    @Autowired
    public void setDocMapper(DocMapper docMapper) {
        this.docMapper = docMapper;
    }

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private DocInfoMapper docInfoMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private WebSocketService webSocketService;

    @Autowired
    public void setContentMapper(ContentMapper contentMapper) {
        this.contentMapper = contentMapper;
    }

    @Override
    public PageResp<DocQueryResp> docList(DocQueryReq req) {
        DocExample example = new DocExample();
        example.setOrderByClause("sort asc");
        DocExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(true);
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Doc> docList = docMapper.selectByExample(example);
        PageInfo<Doc> pageInfo = new PageInfo<>(docList);

//        List<DocQueryResp> respList = new ArrayList<>();
//        for (Doc doc : docList) {
////            DocQueryResp docResp = new DocQueryResp();
////            BeanUtils.copyProperties(doc, docResp);
//            DocQueryResp docResp = CopyUtil.copy(doc, DocQueryResp.class);
//            respList.add(docResp);
//        }
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);
        PageResp<DocQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    @Override
    public List<DocQueryResp> all(Long ebookId) {
        DocExample example = new DocExample();
        DocExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(true);
        criteria.andEbookIdEqualTo(ebookId);
        example.setOrderByClause("sort asc");
        List<Doc> docList = docMapper.selectByExample(example);
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);
        return list;
    }

    @Override
    public void delete(List<String> ids) {
        DocExample example = new DocExample();
        DocExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        docMapper.deleteByExample(example);
    }

    @Override
    public String findContentById(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(content)) {
            return "";
        } else {
            // 浏览量+1
            String ip = RequestContext.getRemoteAddr();
            // 0——标识该字段为阅读
            if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip + "1", 3600 * 24)) {
                docInfoMapper.viewCountIncrement(id);
            }
            return content.getContent();
        }
    }

    @Override
    public void vote(Long id) {
        // 远程IP+doc.id作为key 24小时不能重复
        String ip = RequestContext.getRemoteAddr();
        // 0——标识该字段为点赞
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip + "0", 3600 * 24)) {
            docInfoMapper.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
        // 推送消息
        Doc docDb = docMapper.selectByPrimaryKey(id);
        webSocketService.sendInfo("你的文档【" + docDb.getName() + "】，有人给你点赞啦，快去看看吧！");
    }

    @Override
    public void updateEbookInfo() {
        docInfoMapper.updateEbookInfo();
    }

    @Override
    @Transactional
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        Content content = CopyUtil.copy(req, Content.class);
        Date date = new Date();
        if (ObjectUtils.isEmpty(doc.getId())) {
            // 新增
            Long id = snowFlake.nextId();
            doc.setId(id);
            doc.setCreateTime(date);
            doc.setViewCount(0);
            doc.setVoteCount(0);
            doc.setStatus(true);
            content.setId(id);
            content.setCreateTime(date);
            content.setStatus(true);
            docMapper.insert(doc);
            contentMapper.insertSelective(content);
        } else {
            // 更新
            doc.setUpdateTime(date);
            doc.setStatus(true);
            Long docId = doc.getId();
            docMapper.updateByPrimaryKeySelective(doc);
            content.setId(docId);
            content.setStatus(true);
            content.setUpdateTime(date);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0) {
                content.setCreateTime(date);
                contentMapper.insert(content);
            }
        }
    }

    @Override
    public void delete(Long id) {
        docMapper.deleteByPrimaryKey(id);
    }
}
